<template>
  <view class="time-select flex flex-a">
    <view class="time-pick-input" @click="openPopup">
      <image style="width: 24px; height: 24px" :src="clock" />
      <text class="value">{{ selectValue[0] || "00:00" }}</text>
    </view>
    <text class="sperator">至</text>
    <view class="time-pick-input" @click="openPopup">
      <image style="width: 24px; height: 24px" :src="clock" />
      <text class="value">{{ selectValue[1] || "00:00" }}</text>
    </view>
  </view>
  <uv-picker
    ref="popup"
    :columns="pickerColumns"
    keyName="text"
    @cancel="close"
    @confirm="onConfirm"
  />
</template>

<script setup>
import { ref, watch, computed } from "vue"
import clock from "@/static/svgIcon/clock.svg"
import columns from "./data"
const popup = ref(null)
const props = defineProps({
  value: {
    type: Array,
    default: () => []
  }
})
const selectValue = computed({
  get() {
    return props.value
  },
  set(val) {
    emits("update:value", val)
  }
})
const emits = defineEmits(["update:value"])
const pickerColumns = ref(columns)
const showPicker = ref(false)

const openPopup = () => {
  popup.value.open("bottom")
}
const close = () => {
  popup.value.close()
}
const onConfirm = (value) => {
  const data = value.value.map((v) => v.value)

  const startTimeStamp = timeToTimestamp(data[0])
  const endTime = timeToTimestamp(data[1])
  console.log(startTimeStamp, endTime)

  if (startTimeStamp > endTime) {
    uni.showToast({
      title: "开始时间不能小于结束时间",
      icon: "none"
    })
    return
  }
  emits("update:value", data)
  showPicker.value = false
}

const timeToTimestamp = (timeString) => {
  const [hours, minutes] = timeString.split(":").map(Number)
  const date = new Date()
  date.setHours(hours)
  date.setMinutes(minutes)
  date.setSeconds(0)
  date.setMilliseconds(0)
  return date.getTime()
}
</script>

<style lang="scss" scoped>
.time-pick-input {
  padding: 10rpx 12rpx 12rpx 10rpx;
  border: 1px solid rgba(252, 247, 247, 1);
  border-radius: 6px;
  color: rgba(102, 102, 102, 1);
  display: flex;
  align-items: center;
  .value {
    margin-left: 30rpx;
    font-size: 32rpx;
  }
}
.sperator {
  margin: 0 2px;
}
</style>
